import React, { useState, useEffect } from 'react';
import { Picker, Button } from '@/components/base';
import dayjs, { Dayjs } from 'dayjs';
import { CalendarOutlined, CloseOutlined } from '@ant-design/icons';

export interface DatePickerProps {
  value?: Dayjs;
  onChange?: (value: Dayjs | undefined) => void;
  placeholder?: string;
  disabled?: boolean;
}

export const DatePicker: React.FC<DatePickerProps> = ({
  value,
  onChange,
  placeholder = '请选择日期',
  disabled = false,
}) => {
  const [selectedDate, setSelectedDate] = useState<Dayjs | undefined>(value);

  useEffect(() => {
    if (value) {
      setSelectedDate(value);
    }
  }, [value]);

  // 生成年份选项（当前年份前后50年）
  const currentYear = dayjs().year();
  const years = Array.from({ length: 101 }, (_, i) => currentYear - 50 + i);

  // 生成月份选项
  const months = Array.from({ length: 12 }, (_, i) => i + 1);

  // 生成日期选项（根据年月动态计算）
  const getDaysInMonth = (year: number, month: number) => {
    return dayjs(`${year}-${month}-01`).daysInMonth();
  };

  const days = Array.from(
    { length: getDaysInMonth(selectedDate?.year() || dayjs().year(), selectedDate?.month() || dayjs().month()) },
    (_, i) => i + 1
  );

  const columns = [
    years.map(year => ({ label: `${year}年`, value: year })),
    months.map(month => ({ label: `${month}月`, value: month })),
    days.map(day => ({ label: `${day}日`, value: day })),
  ];

  const handleChange = (values: (string | number)[]) => {
    const [year, month, day] = values as [number, number, number];
    const newDate = dayjs(`${year}-${month}-${day}`);
    setSelectedDate(newDate);
    onChange?.(newDate);
  };

  const handleClear = (e: React.MouseEvent) => {
    e.stopPropagation();
    setSelectedDate(undefined);
    onChange?.(undefined);
  };

  return (
    <Picker
      columns={columns}
      value={selectedDate ? [selectedDate.year(), selectedDate.month(), selectedDate.date()] : [dayjs().year(), dayjs().month()+1, dayjs().date()]}
      onConfirm={handleChange}
    >
      {(items, { open }) => (
        <div style={{ position: 'relative' }}>
          <Button
            block
            onClick={disabled ? undefined : open}
            disabled={disabled}
            style={{
              textAlign: 'left',
            }}
          >
            <CalendarOutlined style={{ marginRight: 4 }} />
            {selectedDate ? selectedDate.format('YYYY-MM-DD') : placeholder}
          </Button>
          {selectedDate && !disabled && (
            <Button
              size="mini"
              style={{
                position: 'absolute',
                right: 8,
                top: '50%',
                transform: 'translateY(-50%)',
                padding: '2px 6px',
                minWidth: 'auto',
                height: '24px',
                backgroundColor: 'transparent',
                border: 'none',
                color: '#999',
              }}
              onClick={handleClear}
            >
              <CloseOutlined />
            </Button>
          )}
        </div>
      )}
    </Picker>
  );
}; 